import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart';
import 'package:flutter_custom_dialog/flutter_custom_dialog.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_html/style.dart';
import 'package:oktoast/oktoast.dart';
import 'package:school_safe_teacher/constans/all_info.dart';
import 'package:school_safe_teacher/constans/constants.dart';
import 'package:school_safe_teacher/constans/route_constants.dart';
import 'package:school_safe_teacher/resourse/app_colors.dart';
import 'package:school_safe_teacher/widget/my_widget.dart';
import 'package:school_safe_teacher/widget/no_message_widget.dart';
import 'action.dart';
import 'state.dart';

Widget buildView(
    HomePageState state, Dispatch dispatch, ViewService viewService) {
  return stateBar(
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
    topIcon(state, dispatch, viewService),
    Expanded(
      child: Container(
        color: AppColors.MainBackColor,
        child: EasyRefresh(
            controller: state.easyRefreshController,
            header: MaterialHeader(completeDuration: Duration(milliseconds: 0)),
            footer: MaterialFooter(),
            firstRefresh: true,
            enableControlFinishRefresh: true,
            enableControlFinishLoad: true,
            onRefresh: () async {
              //下拉刷新
              state.page = 1;
              dispatch(HomePageActionCreator.onRefresh());
            },
            onLoad: () async {
              //上拉加载
              dispatch(HomePageActionCreator.onLoad(++state.page));
            },
            child: _list(state, dispatch, viewService)),
      ),
    ),
  ]));
}

Widget _list(HomePageState state, Dispatch dispatch, ViewService viewService) {
  return ListView.builder(
    padding: EdgeInsets.zero,
    itemBuilder: (BuildContext context, int index) {
      if (index == 0) {
        return Container(
          padding: EdgeInsets.only(top: 15, bottom: 15, left: 36, right: 36),
          //color: AppColors.MainBackColor,
          //
          decoration: BoxDecoration(
            borderRadius:
                BorderRadius.vertical(bottom: Radius.elliptical(10, 10)),
            color: Colors.white,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                  child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                    icon: Image.asset('images/home/home_choose_member@2x.png'),
                    iconSize: 54,
                    onPressed: () {
                      if (AllInfo.instance.token.isNotEmpty) {
                        Navigator.of(viewService.context)
                            .pushNamed(RouteConstants.STUDENTREVIEW);
                      } else {
                        Navigator.of(viewService.context)
                            .pushNamed(RouteConstants.LOGIN);
                      }
                    },
                  ),
                  Text("学生审核"),
                ],
              )),
              Container(
                  child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                    icon: Image.asset('images/home/home_choose_see@2x.png'),
                    iconSize: 54,
                    onPressed: () {
                      if (AllInfo.instance.token.isNotEmpty) {
                        Navigator.of(viewService.context)
                            .pushNamed(RouteConstants.HOMEWORK);
                      } else {
                        Navigator.of(viewService.context)
                            .pushNamed(RouteConstants.LOGIN);
                      }
                    },
                  ),
                  Text("作业下发"),
                ],
              )),
              Container(
                  child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                    icon: Image.asset('images/home/home_choose_leaver@2x.png'),
                    iconSize: 54,
                  ),
                  Text("请假审批"),
                ],
              )),
            ],
          ),
        );
      } else if (index == 1) {
        return Container(
          height: 45,
          child: Row(
            children: [
              Container(
                child: Text("天天有料",
                    style: TextStyle(
                        color: AppColors.deepTextColor,
                        fontSize: 16,
                        fontWeight: FontWeight.bold)),
                margin: EdgeInsets.only(left: 15),
              ),
              Expanded(
                  child: GestureDetector(
                child: Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        child: Text("更多",
                            style: TextStyle(
                              color: AppColors.smallTextColor,
                              fontSize: 12,
                            )),
                      ),
                      Container(
                        margin: EdgeInsets.only(right: 15, left: 5),
                        child: Image.asset(
                          "images/arrow_right@2x.png",
                          width: 5,
                          height: 10,
                        ),
                      ),
                    ],
                  ),
                ),
                onTap: () {
                  if (AllInfo.instance.token.isNotEmpty) {
                    Navigator.of(viewService.context).pushNamed(
                        RouteConstants.NEWS_LIST,
                        arguments: {Constants.FROM_SEARCH: false});
                  } else {
                    Navigator.of(viewService.context).pushNamed(RouteConstants.LOGIN);
                  }
                },
              ))
            ],
          ),
        );
      } else {
        String testImg = "";
        switch (state.items[index - 2].type) {
          case Constants.NEWS_TYPE_1:
            testImg = "images/home/home_item_jingxuan@2x.png";
            break;
          case Constants.NEWS_TYPE_2:
            testImg = "images/home/home_item_zhengce@2x.png";
            break;
          case Constants.NEWS_TYPE_3:
            testImg = "images/home/home_item_gonggao@2x.png";
            break;
        }
        return GestureDetector(
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
              color: Colors.white,
            ),
            margin: EdgeInsets.only(top: 5, left: 15, right: 15, bottom: 5),
            padding: EdgeInsets.only(top: 15, left: 10, right: 10, bottom: 15),
            child: IntrinsicHeight(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Container(
                      height: double.infinity,
                      child: Column(
                        mainAxisSize: MainAxisSize.max,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            state.items[index - 2].title,
                            style: TextStyle(
                                color: AppColors.deepTextColor, fontSize: 15),
                            maxLines: 2,
                            textAlign: TextAlign.start,
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                  child: Image.asset(
                                    testImg,
                                    width: 27.5,
                                    height: 16.5,
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(left: 5),
                                  child: Text(
                                    state.items[index - 2].createTime,
                                    style: TextStyle(
                                        fontSize: 11,
                                        color: AppColors.smallTextColor),
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                      margin: EdgeInsets.only(right: 20),
                    ),
                    flex: 2,
                  ),
                  Expanded(
                    child: Container(
                        child: CachedNetworkImage(
                      imageUrl: state.items[index - 2].imgUrl,
                      errorWidget: (context, url, error) =>
                          Image.asset("images/test_banner@2x.png"),
                      fit: BoxFit.fitWidth,
                    )),
                    flex: 1,
                  )
                ],
              ),
            ),
          ),
          onTap: () {
            if (AllInfo.instance.token.isNotEmpty) {
              Navigator.of(viewService.context)
                  .pushNamed(RouteConstants.NEWS_DETAIL, arguments: {
                Constants.NEWS_DETAIL_ENTITY: state.items[index - 2]
              });
            } else {
              Navigator.of(viewService.context).pushNamed(RouteConstants.LOGIN);
            }
          },
        );
      }
    },
    itemCount: (2 + state.items.length),
  );
}

Widget topIcon(
    HomePageState state, Dispatch dispatch, ViewService viewService) {
  return Container(
    height: 44 + MediaQuery.of(viewService.context).padding.top,
    color: Color(0xFFFFDC21),
    padding: EdgeInsets.only(
      top: MediaQuery.of(viewService.context).padding.top,
      left: 15,
      bottom: 5,
    ),
    child: Row(
      children: [
        GestureDetector(
          child: Row(
            children: [
              Container(
                child: Text(state.classname,
                    style: TextStyle(
                        color: AppColors.deepTextColor,
                        fontSize: 14,
                        fontWeight: FontWeight.bold)),
              ),
              Container(
                margin: EdgeInsets.only(top: 10, left: 3),
                child: Image.asset(
                  "images/home/home_drop-down@2x.png",
                  width: 5,
                  height: 5,
                ),
              )
            ],
          ),
          onTap: () {
            if (AllInfo.instance.token.isNotEmpty) {
              chooseDefaultMember(state, dispatch, viewService);
            } else {
              Navigator.of(viewService.context).pushNamed(RouteConstants.LOGIN);
            }
          },
        ),
        Expanded(
          child: GestureDetector(
            child: Container(
              margin: EdgeInsets.only(right: 12, left: 10),
              padding: EdgeInsets.only(left: 15, top: 7, bottom: 7),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(15),
              ),
              child: Row(
                children: [
                  Image.asset(
                    "images/home_search@2x.png",
                    width: 13,
                    height: 14,
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text(
                    "搜索",
                    style: TextStyle(
                        color: Color(0xFFAAADC0),
                        textBaseline: TextBaseline.alphabetic),
                  )
                ],
              ),
            ),
            onTap: (){
              Navigator.of(viewService.context).pushNamed(
                  RouteConstants.NEWS_LIST,
                  arguments: {Constants.FROM_SEARCH: true});
            },
          ),
        ),
        IconButton(
          icon: Image.asset('images/home_message@2x.png'),
          onPressed: () {
            Navigator.of(viewService.context).pushNamed(RouteConstants.MESSAGE);
          },
          iconSize: 20,
        ),
      ],
    ),
  );
}

void chooseDefaultMember(
    HomePageState state, Dispatch dispatch, ViewService viewService) {
  YYDialog yyDialog = YYDialog().build(viewService.context);
  yyDialog
    ..gravity = Gravity.bottom
    ..width = MediaQuery.of(viewService.context).size.width
    ..widget(Container(
      decoration: BoxDecoration(
          color: Colors.white,
          //设置四周圆角 角度
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(30), topRight: Radius.circular(30))),
      child: ListView.separated(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: state.classList.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: Container(
              child: Text(
                state.classList[index].className,
                textAlign: TextAlign.center,
              ),
              margin: EdgeInsets.only(top: 15, bottom: 15),
            ),
            onTap: () {
              dispatch(HomePageActionCreator.onChooseClassSuccess(
                  state.classList[index].classId.toString()));
              yyDialog.dismiss();
            },
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
        },
      ),
    ))
    ..widget(Platform.isIOS
        ? SizedBox(
            height: MediaQuery.of(viewService.context).padding.bottom,
          )
        : Container())
    ..show();
}
